import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
import defaultRouters from './defaultRouters';
import getUrlParam from '@/utils/index';

NProgress.configure({ showSpinner: false });

// 消除重复进入相同路由的警报
// push方式
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

// replace方式
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes: defaultRouters
});

// 路由拦截
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  let token = getUrlParam('token');
  let redirect = getUrlParam('redirect');
  let language = getUrlParam('language');
  let theme = getUrlParam('theme');
  if (language) {
    localStorage.setItem('language', language);
  }
  if (theme) {
    localStorage.setItem('theme', '#' + theme);
  }
  if (token) {
    store.commit('user/setToken', token);
    let href = window.location.origin;
    if (redirect) {
      href = href + redirect;
    }
    window.location.href = href;
  } else {
    if (store.getters.token) {
      if (store.getters.routes.length) {
        next();
      } else {
        await store.dispatch('permission/generateRoutes');
        next({ path: to.path });
      }
    } else {
      store.commit('user/signOut', to.path);
    }
  }
});

router.afterEach((to, from, next) => {
  NProgress.done();
  document.title = to.meta.title || '思普云平台';
});

export default router;
